import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:openchina/constants/constants.dart'
    show AppColors, AppInfo, AppUrls;
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';

class NewsDetailPage extends StatefulWidget {
  final int id;

  NewsDetailPage({this.id}) : assert(id != null);

  @override
  _NewsDetailPageState createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  FlutterWebviewPlugin _flutterWebviewPlugin = FlutterWebviewPlugin();
  bool _isLoading = true;
  String url;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _flutterWebviewPlugin.onStateChanged.listen((state) {
      if (state.type == WebViewState.startLoad) {
        print('CommonWebPageState WebViewState.startLoad: $state');
        if (mounted) {
          //转菊花消失  mounted 确保当前weiget 在当前渲染树上
          setState(() {
            _isLoading = true;
          });
        }
      } else if (state.type == WebViewState.finishLoad) {
        print('CommonWebPageState WebViewState.finishLoad: $state');
        if (mounted) {
          //转菊花消失  mounted 确保当前weiget 在当前渲染树上
          setState(() {
            _isLoading = false;
          });
        }
      }
    });
    DataUtil.getTokenAccess().then((accessToken) {
      if (accessToken != null && accessToken.length > 0) {
        Map<String, dynamic> params = new Map<String, dynamic>();
        params['access_token'] = accessToken;
        params['id'] = widget.id;
        params['dataType'] = AppInfo.JSON;
        NetUtil.get(AppUrls.NEWS_DETAIL, params).then((data) {
//{"author":"小东c","id":110954,"authorid":2313499,"title":"spider-flow 0.1.0 发布，Java 开源爬虫平台","body":"<style type='text/css'>pre {white-space:pre-wrap;word-wrap:break-word;}</style><p>历时三个多月，第一个正式版发布</p> \n<p>spider-flow 是一个无需写代码的爬虫平台，通过定义流程的方式制定爬虫</p> \n<p>现已有特性如下：</p> \n<ul> \n <li>支持css选择器、正则提取</li> \n <li>支持JSON/XML格式</li> \n <li>支持Xpath/JsonPath提取</li> \n <li>支持多数据源、SQL select/insert/update/delete/批量插入</li> \n <li>支持爬取JS动态渲染的页面</li> \n <li>支持代理</li> \n <li>支持二进制格式、二进制流格式</li> \n <li>支持保存/读取文件(csv、xls、jpg等)</li> \n <li>常用字符串、日期、文件、加解密等函数</li> \n <li>支持流程嵌套</li> \n <li>支持插件扩展(自定义执行器，自定义函数）</li> \n <li>支持HTTP接口</li> \n</ul> \n<p>已有插件如下：
          print('详情数据 $data');
          if (data != null && data.length > 0) {
            Map<String, dynamic> map = json.decode(data);
            setState(() {
              url = map['url'];
            });
          }
        });
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _flutterWebviewPlugin.close();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _appBarTitle = [
      Text(
        '详情',
        style: TextStyle(
          color: Color(AppColors.APPBAR),
        ),
      ),
    ];
    if (_isLoading) {
      _appBarTitle.add(
        SizedBox(
          width: 10.0,
        ),
      );
      _appBarTitle.add(CupertinoActivityIndicator());
    }
    return url == null
        ? Scaffold(
            body: Center(
              child: CupertinoActivityIndicator(),
            ),
          )
        : WebviewScaffold(
            url: url,
            appBar: AppBar(
              title: Row(
                children: _appBarTitle,
              ),
              iconTheme: IconThemeData(
                color: Color(AppColors.APPBAR),
              ),
            ),
            withJavascript: true,
            //允许执行js
            withLocalStorage: true,
            //允许本地存储
            withZoom: true, //允许网页放大缩小
          );
  }
}
